package org.cocos2dx.javascript.Mob;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.MobSDK;
import com.mob.secverify.ui.AgreementPage;
import com.pelbs.book99998.R;

import org.json.JSONException;


public class NormalLoginDialog extends Dialog {
    private Context context;
    private View contentView;
    private String url;
    public NormalLoginDialog(Context context) {
        super(context, R.style.other_telphone_login);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater inflater = LayoutInflater.from(this.context);
        contentView = inflater.inflate(R.layout.one_key_login, null);
        setContentView(contentView);
        this.initOwnView();
        this.setCanceledOnTouchOutside(false);
        this.setCancelable(false);

        this.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                else{
                    return false;
                }
            }
        });
    }

    private void initOwnView() {
        TextView tvOwnPhone = contentView.findViewById(R.id.login_phone_number);

        String phoneNumber = SdkSetting.getSetting(context, "phoneNumber");

        if (phoneNumber != ""){
            tvOwnPhone.setText(PhoneUtils.phoneEncrypt(phoneNumber));
            contentView.findViewById(R.id.one_key_login_checkbox).setVisibility(View.VISIBLE);
            TextView tvAgreement = contentView.findViewById(R.id.login_use_this_number_privacy);
            tvAgreement.setText(buildSpanString());
            tvAgreement.setHighlightColor(context.getResources().getColor(android.R.color.transparent));
            tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        }
        else{
            tvOwnPhone.setText(R.string.no_phone_number);
            TextView tvAgreement = contentView.findViewById(R.id.login_use_this_number_privacy);
            tvAgreement.setText(R.string.no_sim_card);
            tvAgreement.setHighlightColor(context.getResources().getColor(android.R.color.transparent));
            tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
            contentView.findViewById(R.id.one_key_login_checkbox).setVisibility(View.INVISIBLE);
        }

        contentView.findViewById(R.id.login_login_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击自己登录按钮时需要将默认的复选框设置为选中，并且点击原有的授权页面登录按钮

                if (!((CheckBox)contentView.findViewById(R.id.one_key_login_checkbox)).isChecked()){
                    Toast.makeText(context, "请先阅读并且同意隐私政策以及用户使用协议", Toast.LENGTH_LONG).show();
                    return;
                }

                String phoneNumber = SdkSetting.getSetting(context, "phoneNumber");

                if (phoneNumber != ""){
                    try {
                        PhoneLoginMgr.getInstance().loginSucc(phoneNumber);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    contentView.findViewById(R.id.login_login_btn).setEnabled(false);
                }
                else{
                    PhoneLoginMgr.getInstance().otherPhoneLogin();
                }

            }
        });

        contentView.findViewById(R.id.login_login_btn).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        if(v.getId() == R.id.login_login_btn){
                            contentView.findViewById(R.id.login_login_btn).setScaleX((float)0.95);
                            contentView.findViewById(R.id.login_login_btn).setScaleY((float)0.95);
                        }
                        break;


                    case MotionEvent.ACTION_UP:
                        if(v.getId() == R.id.login_login_btn){
                            contentView.findViewById(R.id.login_login_btn).setScaleX(1);
                            contentView.findViewById(R.id.login_login_btn).setScaleY(1);
                        }
                        break;
                }
                return false;
            }
        });


        contentView.findViewById(R.id.other_phone_login_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhoneLoginMgr.getInstance().otherPhoneLogin();
            }
        });

        contentView.findViewById(R.id.login_question_btn).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                QuestionDialog dlg = new QuestionDialog(context);
                dlg.show();
            }
        });
    }

    private SpannableString buildSpanString() {
        String operatorText = "";
        if (OperatorUtils.getCellularOperatorType() == 1) {
            operatorText = "中国移动认证服务条款 |";
            url = "https://wap.cmpassport.com/resources/html/contract.html";
        } else if (OperatorUtils.getCellularOperatorType() == 2) {
            operatorText = "中国联通认证服务条款 |";
            url = "https://ms.zzx9.cn/html/oauth/protocol2.html";
        } else if (OperatorUtils.getCellularOperatorType() == 3) {
            operatorText = "中国电信认证服务条款 |";
            url = "https://e.189.cn/sdk/agreement/content.do?type=main&appKey=&hidetop=true&returnUrl=";
        }

        String ageementText = "";
        if (OperatorUtils.getCellularOperatorType() == 1 ||
                OperatorUtils.getCellularOperatorType() == 2 ||
                OperatorUtils.getCellularOperatorType() == 3){
            ageementText = "我已阅读同意  " + operatorText + " 隐私政策 |" +
                    " 用户使用协议 | 授权秒验使用本机号码登录";
        }
        else{
            ageementText = "同意" + operatorText + " 隐私政策 |" +
                    " 用户使用协议 | 授权秒验使用本机号码登录";
        }
        String cusPrivacy1 = "隐私政策 |";
        String cusPrivacy2 = "用户使用协议 |";
        String cusPrivacy3 = "其他隐私政策";
        int baseColor = MobSDK.getContext().getResources().getColor(R.color.sec_verify_demo_text_color_common_black);
        int privacyColor = Color.parseColor("#FF2073D1");
        int cusPrivacyColor1 = Color.parseColor("#FF2073D1");
        int cusPrivacyColor2 = Color.parseColor("#FF2073D1");
        int cusPrivacyColor3 = Color.parseColor("#FFFE7A4E");
        SpannableString spanStr = new SpannableString(ageementText);
        int privacyIndex = ageementText.indexOf(operatorText);
        spanStr.setSpan(new ForegroundColorSpan(baseColor)
                , 0, ageementText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置文字的单击事件
        spanStr.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                gotoAgreementPage(url, "");
            }
        }, privacyIndex, privacyIndex + operatorText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置文字的前景色
        spanStr.setSpan(new ForegroundColorSpan(privacyColor), privacyIndex, privacyIndex + operatorText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (!TextUtils.isEmpty(cusPrivacy1)) {
            int privacy1Index = ageementText.indexOf(cusPrivacy1);
            //设置文字的单击事件
            spanStr.setSpan(new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);
                }

                @Override
                public void onClick(View widget) {
                    gotoAgreementPage("http://www.fjbgwl.com/%E9%9A%90%E7%A7%81%E6%94%BF%E7%AD%96.html", null);
//					if (wrapper != null && wrapper.cusAgreement1Clicked != null){
//						wrapper.cusAgreement1Clicked.handle();
//					}
                }
            }, privacy1Index, privacy1Index + "《自有隐私政策》".length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            //设置文字的前景色
            spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor1), privacy1Index, privacy1Index + cusPrivacy1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!TextUtils.isEmpty(cusPrivacy2)) {
            int privacy2Index = ageementText.lastIndexOf(cusPrivacy2);
            //设置文字的单击事件
            spanStr.setSpan(new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);
                }

                @Override
                public void onClick(View widget) {
                    gotoAgreementPage("http://www.fjbgwl.com/%E7%94%A8%E6%88%B7%E5%8D%8F%E8%AE%AE.html\n", null);
                }
            }, privacy2Index, privacy2Index + cusPrivacy2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor2), privacy2Index, privacy2Index + cusPrivacy2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        /*
        if (!TextUtils.isEmpty(cusPrivacy3)) {
            int privacy3Index = ageementText.lastIndexOf(cusPrivacy3);
            //设置文字的单击事件
            spanStr.setSpan(new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);
                    ds.linkColor = Color.parseColor("#FFFFFF");
                }

                @Override
                public void onClick(View widget) {
                    Log.e("gotoAgreementPage3", "spanStr gotoAgreementPage3");
                    gotoAgreementPage("https://www.baidu.com", null);
                }
            }, privacy3Index, privacy3Index + cusPrivacy3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            //设置文字的前景色
            spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor3), privacy3Index, privacy3Index + cusPrivacy3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
         */
        return spanStr;
    }

    public void enableLoginBtn(){
        contentView.findViewById(R.id.login_login_btn).setEnabled(true);
    }

    //可替换为跳转自己的webview
    private static void gotoAgreementPage(String agreementUrl, String title) {
        if (TextUtils.isEmpty(agreementUrl)) {
            Log.e("OtherPhoneDialog", "gotoAgreementPage return");
            return;
        }
        AgreementPage page = new AgreementPage();
        Intent i = new Intent();
        i.putExtra("extra_agreement_url", agreementUrl);
        if (!TextUtils.isEmpty(title)) {
            i.putExtra("privacy", title);
        }
        page.show(MobSDK.getContext(), i);
    }
}
